package com.boding.power.controller;

import java.util.Date;

import org.apache.commons.lang3.StringUtils;

import com.boding.power.model.GoodsPower;
import com.boding.power.model.News;
import com.boding.power.utils.DataGrid;
import com.boding.power.utils.Dates;
import com.boding.power.utils.QiNiuUtil;
import com.jfinal.core.ActionKey;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Page;

public class InfoController extends Controller {
	public void pubNewsUI() {
		render("pubNews.jsp");
	}

	public void listNewsUI() {
		render("newsList.jsp");
	}

	public void listnews() {
		Integer rows = getParaToInt("rows");
		Integer page = getParaToInt("page");
		Page<News> pages = News.dao.paginate(page, rows, "select *",
				" from news order by date desc");
		DataGrid<News> dataGrid = new DataGrid<News>(pages);
		renderJson(dataGrid);
	}

	@ActionKey("/info")
	public void info() {
		Integer id = getParaToInt("id");
		setAttr("news", News.dao.findById(id));
		renderJsp("/info.jsp");
	}

	@ActionKey("/list")
	public void list() {
		String name = getPara("name");
		setAttr("title", name);
		setAttr("news", News.dao.findByType(name));
		renderJsp("/list.jsp");
	}

	public void delnews() {
		Integer id = getParaToInt("id");
		if (News.dao.deleteById(id)) {
			renderJson("删除成功");
		} else {
			renderJson("删除失败");
		}
	}

	public void updatenews() {
		News news = getModel(News.class, "", true);
		news.set("date", new Date());
		news.update();
		redirect("/admin/info/listNewsUI");
	}

	public void operateInfo() {
		String type = getPara("oper");
		Integer id = getParaToInt("id");
		News news = News.dao.findById(id);
		setAttr("news", news);
		if (StringUtils.equals(type, "edit")) {
			render("editNews.jsp");
		}
	}

	public void addnews() {
		News news = getModel(News.class, "", true);
		news.setImgurl(news.getImgurl().trim());
		news.setDate(new Date());
		news.save();
		redirect("/admin/info/listNewsUI");
	}

	public void delImage() {
		String key = getPara("key");
		Integer id = getParaToInt("id");
		if (StringUtils.isNotEmpty(key) && StringUtils.isNotBlank(key)) {
			QiNiuUtil.delFile(key);
			// 更新数据库商品的图片信息
			News news = News.dao.findById(id);
			String pics = news.getImgurl();
			String newPics = pics.replace(key, "");
			news.setImgurl(newPics);
			news.update();
			setAttr("key", key);
			renderText(key);
		} else {
			renderText("删除失败");
		}
	}

	public void getImages() {
		Integer id = getParaToInt(0);
		News news = News.dao.findById(id);
		if (news != null && StringUtils.isNotBlank(news.getImgurl())
				&& StringUtils.isNotEmpty(news.getImgurl())) {
			String[] images = news.getImgurl().split(" ");
			renderJson(images);
		} else {
			renderNull();
		}
	}

}
